/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * DBServerDesign.java
 *
 * Created on May 5, 2012, 11:13:14 AM
 */
package db.server.GUI;

import db.server.DTO.RowDTO;
import db.server.DTO.DesignTableDTO;
import db.server.BUS.DesignBUS;

import java.awt.event.ActionEvent;

import java.util.ArrayList;
import java.util.List;

import javax.swing.DefaultCellEditor;
import javax.swing.JComboBox;
import javax.swing.JLabel;
import javax.swing.JTabbedPane;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableColumn;

/**
 *
 * @author QuangKhai
 */
public final class DBServerDesign extends javax.swing.JPanel {
    private DesignBUS designTableBUS;
    private DesignTableDTO tableDTO;
    private DefaultTableModel tables = new DefaultTableModel(); 
    
    private JTabbedPane tabpane;
    private JLabel lb_status;
    private String path;
        
    /** Creates new form DBServerDesign */
    public DBServerDesign(JTabbedPane tabPane, String path, JLabel label) {
        initComponents();
        
        this.lb_status = label;
        this.tabpane = tabPane;
        this.path = path;
        this.designTableBUS = new DesignBUS();
        this.tables = (DefaultTableModel) table.getModel();    
        tb_address.setText(path);
        
        insertRow();
    }
    
    /** Creates new form DBServerDesign */
    public DBServerDesign(JTabbedPane tabPane, String path, DesignTableDTO tableDTO, JLabel label){
        initComponents();
        
        this.lb_status = label;                
        this.tableDTO = tableDTO;
        this.tabpane = tabPane;
        this.path = path;
        designTableBUS = new DesignBUS();
        tables = (DefaultTableModel) table.getModel();    
        
        showTable();
    }
    
    ///Support call save desgin table from outside
    public void save(){
        ActionEvent evt = null;
        bt_okActionPerformed(evt);
    }
    
    ///Get value into DesignTableDTO to call save table with it
    public void saveTable(){
        System.out.println("Save " + path);
        DesignTableDTO designtableDTO = new DesignTableDTO();
        designtableDTO.setTableName(tb_tablename.getText());

        List<RowDTO> lstRows = new ArrayList<RowDTO>();
        for(int i = 0; i < table.getRowCount() - 1; i++){
            RowDTO row = new RowDTO();

            row.setColumnName(table.getValueAt(i, 0).toString());
            row.setDataType(table.getValueAt(i, 1).toString());
            if(table.getValueAt(i, 2).equals(true)){
                row.setAllowNulls(true);
            } else{
                row.setAllowNulls(false);
            }

            if(table.getValueAt(i, 3).equals(true)){
                row.setPrimaryKey(true);
            }else{
                row.setPrimaryKey(false);
            }

            lstRows.add(row);
        }

        designtableDTO.setLstRows(lstRows);
        
        designTableBUS.saveDesignTable(designtableDTO, tb_address.getText());
    }
    
    ///Get DesignTableDTO to show screen
    public void showTable(){
        lb_status.setText(tableDTO.getTableName() + "Table");
        tb_tablename.setText(tableDTO.getTableName());        
        tb_tablename.setToolTipText(tableDTO.getTableName());
        tb_address.setText(path);
        tb_address.setToolTipText(path);
        
        List<RowDTO> lstRow = new ArrayList<RowDTO>();
        lstRow = tableDTO.getLstRows();
        int rowCount = tableDTO.getLstRows().size();
        
        for(int i = 0; i < rowCount; i++){
            tables.insertRow(table.getRowCount(), new Object[]{lstRow.get(i).getColumnName(), lstRow.get(i).getDataType(), lstRow.get(i).isAllowNulls(), lstRow.get(i).isPrimaryKey()});
        }
        
        insertRow();
    }
    
    ///Insert a new row in JTable
    public void insertRow(){
        TableColumn dataType = table.getColumnModel().getColumn(1);

        JComboBox comboBox = new JComboBox();
        comboBox.addItem("int");
        comboBox.addItem("varchar");    

        dataType.setCellEditor(new DefaultCellEditor(comboBox));        

        tables.insertRow(table.getRowCount(), new Object[]{"", "", true, false}); 
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jLabel1 = new javax.swing.JLabel();
        tb_tablename = new javax.swing.JTextField();
        jScrollPane1 = new javax.swing.JScrollPane();
        table = new javax.swing.JTable();
        bt_remove = new javax.swing.JButton();
        bt_ok = new javax.swing.JButton();
        bt_cancel = new javax.swing.JButton();
        jLabel2 = new javax.swing.JLabel();
        tb_address = new javax.swing.JTextField();

        setAutoscrolls(true);
        setPreferredSize(new java.awt.Dimension(650, 323));

        jLabel1.setFont(new java.awt.Font("Cambria", 0, 12));
        jLabel1.setText("Table name");

        tb_tablename.setFont(new java.awt.Font("Cambria", 0, 12)); // NOI18N

        table.setFont(new java.awt.Font("Cambria", 0, 12));
        table.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {

            },
            new String [] {
                "Column Name", "Data Type", "Allow Nulls", "Primary Key"
            }
        ) {
            Class[] types = new Class [] {
                java.lang.String.class, java.lang.Object.class, java.lang.Boolean.class, java.lang.Boolean.class
            };

            public Class getColumnClass(int columnIndex) {
                return types [columnIndex];
            }
        });
        table.setColumnSelectionAllowed(true);
        table.setDoubleBuffered(true);
        table.setDragEnabled(true);
        table.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                tableMouseClicked(evt);
            }
        });
        table.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyTyped(java.awt.event.KeyEvent evt) {
                tableKeyTyped(evt);
            }
        });
        jScrollPane1.setViewportView(table);
        table.getColumnModel().getSelectionModel().setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION);

        bt_remove.setFont(new java.awt.Font("Cambria", 0, 12)); // NOI18N
        bt_remove.setText("Remove");
        bt_remove.setToolTipText("Remove");
        bt_remove.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                bt_removeActionPerformed(evt);
            }
        });

        bt_ok.setFont(new java.awt.Font("Cambria", 0, 12)); // NOI18N
        bt_ok.setText("OK");
        bt_ok.setToolTipText("OK");
        bt_ok.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                bt_okActionPerformed(evt);
            }
        });

        bt_cancel.setFont(new java.awt.Font("Cambria", 0, 12)); // NOI18N
        bt_cancel.setText("Cancel");
        bt_cancel.setToolTipText("Cancel");
        bt_cancel.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                bt_cancelActionPerformed(evt);
            }
        });

        jLabel2.setFont(new java.awt.Font("Cambria", 0, 12));
        jLabel2.setText("Address");

        tb_address.setEditable(false);
        tb_address.setFont(new java.awt.Font("Cambria", 0, 12)); // NOI18N
        tb_address.setAutoscrolls(false);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
        this.setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jLabel1)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(tb_tablename, javax.swing.GroupLayout.PREFERRED_SIZE, 106, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(18, 18, 18)
                        .addComponent(jLabel2)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(tb_address, javax.swing.GroupLayout.DEFAULT_SIZE, 314, Short.MAX_VALUE))
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 549, Short.MAX_VALUE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(bt_remove, javax.swing.GroupLayout.PREFERRED_SIZE, 75, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(bt_ok, javax.swing.GroupLayout.PREFERRED_SIZE, 75, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(bt_cancel, javax.swing.GroupLayout.PREFERRED_SIZE, 75, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel1)
                    .addComponent(tb_tablename, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(tb_address, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel2))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(bt_remove)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(bt_ok)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(bt_cancel))
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 274, Short.MAX_VALUE))
                .addContainerGap())
        );
    }// </editor-fold>//GEN-END:initComponents

private void bt_cancelActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_bt_cancelActionPerformed
// TODO add your handling code here:
    tabpane.remove(tabpane.getSelectedIndex());
    lb_status.setText("Design table is closed!");
}//GEN-LAST:event_bt_cancelActionPerformed

private void bt_okActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_bt_okActionPerformed
// TODO add your handling code here:
    saveTable();
    lb_status.setText("Design table saved!");
}//GEN-LAST:event_bt_okActionPerformed

private void tableMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_tableMouseClicked
// TODO add your handling code here:
    if(table.getSelectedColumn() == 3){
        if(table.getValueAt(table.getSelectedRow(), 3).toString().compareTo("true") == 0){
            table.setValueAt(false, table.getSelectedRow(), 2);            
        }
    }
    
    if(table.getSelectedColumn() == 2){
        if(table.getValueAt(table.getSelectedRow(), 3).toString().compareTo("true") == 0){
            table.setValueAt(false, table.getSelectedRow(), 2);            
        }
    }   
}//GEN-LAST:event_tableMouseClicked

private void bt_removeActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_bt_removeActionPerformed
// TODO add your handling code here:
    if(table.getSelectedRow() != table.getRowCount() - 1){
        tables.removeRow(table.getSelectedRow());
        lb_status.setText("Done");
    }else{
        lb_status.setText("You can't remove an empty row");
    }
}//GEN-LAST:event_bt_removeActionPerformed

private void tableKeyTyped(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_tableKeyTyped
// TODO add your handling code here:
    if(table.getSelectedRow() == table.getRowCount() - 1){
        insertRow();
    }
}//GEN-LAST:event_tableKeyTyped
    
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton bt_cancel;
    private javax.swing.JButton bt_ok;
    private javax.swing.JButton bt_remove;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTable table;
    private javax.swing.JTextField tb_address;
    private javax.swing.JTextField tb_tablename;
    // End of variables declaration//GEN-END:variables
}
